package com.chii.color.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chii.color.client.UserClient;
import com.chii.color.po.ColorHistory;
import com.chii.color.po.ResponeInfo;
import com.chii.color.po.User;
import com.chii.color.service.HistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.List;

@Api(value = "历史记录controller", tags = {"历史记录"})
@Validated
@RestController
public class HistoryController {
    private Logger logger = LogManager.getLogger(HistoryController.class);
    @Autowired
    private HistoryService historyService;
    @Autowired
    private UserClient userClient;

    @ApiOperation(value = "获取历史记录")
    @RequestMapping(value = "history", method = RequestMethod.GET)
    public ResponeInfo getHistory(@NotBlank(message = "username 不允许为空") @ApiParam(name = "username", value = "用户名") @RequestParam("username") String username) throws IOException {
        ResponeInfo responeInfo = new ResponeInfo();
        ResponeInfo<User> userResponeInfo = userClient.getUserByUsernameFromUser(username);
        List<ColorHistory> historyList = historyService.getByUserId(userResponeInfo.getData().getId());

        JSONArray historyArray = new JSONArray();
        for (ColorHistory history : historyList) {
            JSONObject historyUrl = new JSONObject();
            historyUrl.put("input", history.getInput());
            historyUrl.put("output", history.getOutput());
            historyUrl.put("id", history.getId());
            historyArray.add(historyUrl);
        }
        responeInfo.setData(historyArray);
        return responeInfo;
    }

    @ApiOperation(value = "删除历史记录")
    @RequestMapping(value = "history", method = RequestMethod.DELETE)
    public ResponeInfo delHistory(@ApiParam(name = "username", value = "用户名") @RequestParam("username") String username,
                                  @ApiParam(name = "historyId", value = "历史id") @RequestParam("historyId") Integer historyId) throws IOException {
        ResponeInfo responeInfo = new ResponeInfo();
        int result = historyService.delById(historyId);
        if (result == 1) {
            responeInfo.setData("删除成功");
        } else {
            responeInfo.setData("删除失败");

        }
        return responeInfo;
    }
}
